﻿
using MesAPI.Extensions.AuthContext;
using MesAPI.Models.Account;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PublicData;
using XinjeMesProgram.Entities;
using XinjeMesProgram.Entities.RoleAndUser;
using XinjeMesProgram.Entities.User;

namespace MesAPI.Controllers.Account
{
    /// <summary>
    /// 权限控制Controller.
    /// </summary>
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class AccountController : ControllerBase
    {
        private ResponseModel response = new ResponseModel();

        /// <summary>
        /// 登录成功获取用户权限.
        /// </summary>
        /// <returns>.</returns>
        [HttpGet]
        [Authorize]
        public ResponseModel Profile()
        {
            using (var dbContext = new FactoryMesContext())
            {
                MesUserRole user = dbContext.MesUserRole.FirstOrDefaultAsync(x => x.ID == AuthContextService.CurrentUser.UserID).Result; // 当前用户实体
                if (user == null)
                {
                    this.response.SetFailed("用户不存在");
                    return this.response;
                }

                List<AuthMenu> menus = dbContext.AuthMenu.Where(x => x.Status == CommonEnum.Status.Normal).ToList();   // 所有页面

                string sqlPermission = string.Empty;
                if (user.UserType == UserType.SuperAdministator)
                {
                    sqlPermission = @"SELECT P.Code AS PermissionCode, P.ActionCode AS PermissionActionCode, P.Name AS PermissionName, P.Type AS PermissionType, 
                        M.Name AS MenuName, M.Guid AS MenuGuid, M.Alias AS MenuAlias, M.IsDefaultRouter 
                        FROM AuthPermission AS P INNER JOIN AuthMenu AS M ON M.Guid = P.MenuGuid";
                }
                else
                {
                    sqlPermission = @"SELECT P.Code AS PermissionCode, P.ActionCode AS PermissionActionCode, P.Name AS PermissionName, P.Type AS PermissionType, 
                        M.Name AS MenuName, M.Guid AS MenuGuid, M.Alias AS MenuAlias, M.IsDefaultRouter 
                        FROM AuthRolePermissionMapping AS RPM LEFT JOIN AuthPermission AS P ON P.Code = RPM.PermissionCode INNER JOIN AuthMenu AS M ON M.Guid = P.MenuGuid
                        WHERE P.Status = 1 AND EXISTS (SELECT 1 FROM AuthUserRoleMapping AS URM WHERE URM.UserGuid={0} AND URM.RoleCode=RPM.RoleCode)";//查询当前登录用户拥有的权限集合(非管理员)
                }

                List<PermissionWithMenu> permissions = dbContext.PermissionWithMenu.FromSqlRaw(sqlPermission, user.ID).ToList();

                List<string> allowPages = new List<string> { };
                if (user.UserType == UserType.SuperAdministator)
                {
                    allowPages.AddRange(menus.Select(x => x.Alias));
                }
                else
                {
                    foreach (var permission in permissions)
                    {
                        allowPages.AddRange(this.FindParentMenuAlias(menus, permission.MenuGuid));
                    }
                }

                allowPages = allowPages.Distinct().ToList();
                Dictionary<string, List<string>> pagePermissions = permissions.GroupBy(x => x.MenuAlias).ToDictionary(g => g.Key, g => g.Select(x => x.PermissionActionCode).ToList());

                this.response.SetData(new
                {
                    access = Array.Empty<string>(),
                    //avator = user.Avatar ?? string.Empty,
                    user_guid = user.ID,
                    user_name = user.UserName,
                    grade = (int)user.UserType,
                    pages = allowPages,
                    permissions = pagePermissions,
                    //logoText = user.LogoName ?? string.Empty,
                    role = user.RoleCode,
                    depId = user.DepId,
                    ProductGroup = user.ProductGroup,
                });
            }

            return this.response;
        }

        /// <summary>
        /// 用户退出登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public ResponseModel Logout(AccoutUserModel model)
        {
            using (var _dbContext = new FactoryMesContext())
            {
                if (_dbContext.MesUserRole.Count(u => u.UserName == model.UserName) > 0)
                {
                    response.SetFailed("用户名已存在！");
                    return response;
                }
            }
            response.SetSuccess();
            return response;
        }

        #region 私有方法
        /// <summary>
        /// 展示权限树.
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="parentGuid"></param>
        /// <returns></returns>
        [HttpPost]
        private List<string> FindParentMenuAlias(List<AuthMenu> menus, string parentGuid)
        {
            var pages = new List<string>();
            var parent = menus.FirstOrDefault(x => x.Guid == parentGuid);
            if (parent != null)
            {
                if (!pages.Contains(parent.Alias))
                {
                    pages.Add(parent.Alias);
                }
                else
                {
                    return pages;
                }

                if (parent.ParentGuid != string.Empty)
                {
                    pages.AddRange(this.FindParentMenuAlias(menus, parent.ParentGuid));
                }
            }

            return pages.Distinct().ToList();
        }

        /// <summary>
        /// 用户注销.
        /// </summary>
        /// <param name="userId">用户id.</param>
        /// <param name="regGroupId">用户组.</param>
        /// <returns>返回成功or失败.</returns>
        private ResponseModel Logoff(string userId, string regGroupId)
        {

            if (AuthContextService.CurrentUser.UserType != UserType.SuperAdministator)
            {
                using (FactoryMesContext dbContext = new FactoryMesContext())
                {
                    dbContext.Database.ExecuteSqlRaw(string.Format("delete from AuthUser where Guid = '{0}'", userId));
                    dbContext.Database.ExecuteSqlRaw(string.Format("delete from authuserrolemapping where UserGuid = '{0}'", userId));
                    dbContext.SaveChanges();
                    //LogDataSQLFun.SaveUserLog("注销账号", AuthContextService.CurrentUser.UserName, userId, string.Empty, "-", regGroupId);
                }
            }

            return this.response;
        }
        #endregion
    }
}
